import api from '../config/api.js'
import util from '../utils/util.js'
import autoLogin from '../utils/autoLogin.js'
import { HEADER } from '../config/api.js'

export default function request(api, method, data, {noAuth = false,noVerify = false}) {
  let header = HEADER
  if (!noAuth) {
    if (!util.checkLogin()) return autoLogin().then(res => {
      request(api, method, data, {
        noAuth,
        noVerify
      })
    })
  }

  if (getApp().globalData.access_token && !noAuth) header['Access_Token'] = getApp().globalData.access_token

  return new Promise((reslove, reject) => {
    wx.request({
      url: api,
      method: method || 'GET',
      header: header,
      data: data || {},
      success: res => {
        if (noVerify) reslove(res.data, res)
        else if (res.data.status === 1) reslove(res.data, res)
        else if (('' + res.data.status).includes(40000)) {
          util.logout()
          util.checkLogin()
        } else reject(res.data.msg || '系统错误')
      },
      fail: err => {
        reject('请求失败')
      }
    })
  })
}

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt) => request(api, method, data, opt || {})
})